package top.bluesword.spel.expression;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;

import java.util.Map;

/**
 * @author 李林峰
 */
public class MapPropertyAccessor implements PropertyAccessor {

    @Override
    public Class<?>[] getSpecificTargetClasses() {
        return new Class[]{Map.class};
    }

    @Override
    public boolean canRead(EvaluationContext context, Object target, String name) {
        return target instanceof Map;
    }

    @Override
    public TypedValue read(EvaluationContext context, Object target, String name) {
        if (target instanceof Map<?,?> map) {
            return new TypedValue(map.get(name));
        }
        return TypedValue.NULL;
    }

    @Override
    public boolean canWrite(EvaluationContext context, Object target, String name) {
        return target instanceof Map;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public void write(EvaluationContext context, Object target, String name, Object newValue) {
        if (target instanceof Map map) {
            map.put(name, newValue);
        }
    }
}
